Explicit conversions

From Cppreference

Jump to: navigation, search

Converts between types when no implicit conversion exists.

Contents

[edit] Syntax

const_cast < type > ( expression )
static_cast < type > ( expression )
dynamic_cast < type > ( expression )
reinterpret_cast < type > ( expression )

All expressions return an object of type type .

[edit] Explanation

All above conversion operators compute the value of expression, convert it to type and return the resulting value. Each conversion can take place only in specific circumstances or the program is ill formed.

[edit] const_cast

Casts type to an equivalent type with different cv-qualifiers.

[edit] static_cast

Casts type to an non-equivalent type. Implicit conversions of cv-qualifiers can also be applied, however neither constness nor volatility can be casted away.

[edit] dynamic_cast

Casts type to an non-equivalent type using run-time check if required. Implicit conversions of cv-qualifiers can also be applied, however neither constness nor volatility can be casted away. Run-time check is performed when casting a polymorphic class to one of its base classes.

If the casted type is a pointer, the pointed object is checked whether it is the requested base class. If the check succeeds, pointer to the requested base class is returned, otherwise NULL pointer is returned.

If the casted type is a reference, the pointed object is checked whether it is the requested base class. If the check succeeds, reference to the requested base class is returned, otherwise std::bad_cast is thrown.

[edit] reinterpret_cast

Casts type to an non-equivalent type. Implicit conversions of cv-qualifiers can also be applied, however neither constness nor volatility can be casted away. No restrictions an casted types are applied.

[edit] Keywords

const_cast, static_cast, dynamic_cast, reinterpret_cast

[edit] Example